#!/usr/bin/env python3
"""
更新热门品牌数据脚本
将指定的品牌ID和名称对应起来，为后续通过品牌ID获取车辆数据做准备
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app import app, db
from models.car_model import Brand

# 热门品牌数据（ID, 品牌名称）- 去除蔚来，AITO改为鸿蒙智行
HOT_BRANDS = [
    (460, '奇瑞'),
    (465, '奥迪'),
    (464, '奔驰'),
    (474, '宝马'),
    (548, '比亚迪'),
    (284, '鸿蒙智行'),
    (572, '特斯拉'),
    (439, '吉利汽车'),
    (641, '长安')
]

def update_hot_brands():
    """更新热门品牌数据"""
    with app.app_context():
        try:
            # 检查数据库连接
            db.create_all()
            
            # 更新或创建热门品牌
            for brand_id, brand_name in HOT_BRANDS:
                # 检查品牌是否已存在
                existing_brand = Brand.query.get(brand_id)
                
                if existing_brand:
                    # 更新现有品牌
                    existing_brand.brand_name = brand_name
                    print(f"更新品牌: ID={brand_id}, 名称={brand_name}")
                else:
                    # 创建新品牌
                    new_brand = Brand(
                        brand_id=brand_id,
                        brand_name=brand_name,
                        brand_intro=f'{brand_name}品牌介绍'
                    )
                    db.session.add(new_brand)
                    print(f"创建品牌: ID={brand_id}, 名称={brand_name}")
            
            # 提交更改
            db.session.commit()
            print("热门品牌数据更新完成！")
            
            # 验证更新结果
            print("\n当前热门品牌列表:")
            for brand_id, brand_name in HOT_BRANDS:
                brand = Brand.query.get(brand_id)
                if brand:
                    print(f"ID: {brand.brand_id}, 名称: {brand.brand_name}")
            
        except Exception as e:
            print(f"更新品牌数据时出错: {e}")
            db.session.rollback()

if __name__ == '__main__':
    print("开始更新热门品牌数据...")
    update_hot_brands()
    print("\n热门品牌ID列表（用于后续API调用）:")
    for brand_id, brand_name in HOT_BRANDS:
        print(f"{brand_name}: {brand_id}")